Stack Using Linked List Algorithm

The Stack Using Linked List Algorithm is a dynamic data structure that implements a stack by utilizing a linked list. A stack is a linear data structure that follows the Last In First Out (LIFO) principle, meaning that the most recently added element is always the first one to be removed. This is similar to a real-life stack of objects, such as a stack of plates, where the top plate is always the first to be taken off. In a linked list, elements are stored in nodes, which contain a reference to the next node in the list. By using a linked list to implement a stack, the algorithm allows for efficient insertion and deletion of elements at the top of the stack, as well as dynamic resizing of the stack. In the stack using a linked list algorithm, a top pointer is maintained to always point to the top element (i.e., the most recently added element) of the stack. The main operations that can be performed on a stack are push, pop, and peek. The push operation adds an element to the top of the stack, while the pop operation removes the top element from the stack. The peek operation simply returns the value of the top element without removing it. To perform the push operation, a new node is created with the given value, and its next pointer is set to the current top node. The top pointer is then updated to point to the newly added node. To perform the pop operation, the top pointer is updated to point to the next node in the list, effectively removing the current top node from the stack. To perform the peek operation, the value of the top node is returned. Since these operations only involve the top node and updating pointers, the time complexity of these operations is constant, O(1).
#include <iostream>
using namespace std;

struct node
{
	int val;
	node *next;
};

node *top;

void push(int x)
{
	node *n = new node;
	n->val = x;
	n->next = top;
	top = n;
}

void pop()
{
	if (top == NULL)
	{
		cout << "\nUnderflow";
	}
	else
	{
		node *t = top;
		cout << "\n"
			 << t->val << " deleted";
		top = top->next;
		delete t;
	}
}

void show()
{
	node *t = top;
	while (t != NULL)
	{
		cout << t->val << "\n";
		t = t->next;
	}
}

int main()
{
	int ch, x;
	do
	{
		cout << "\n1. Push";
		cout << "\n2. Pop";
		cout << "\n3. Print";
		cout << "\nEnter Your Choice : ";
		cin >> ch;
		if (ch == 1)
		{
			cout << "\nInsert : ";
			cin >> x;
			push(x);
		}
		else if (ch == 2)
		{
			pop();
		}
		else if (ch == 3)
		{
			show();
		}
	} while (ch != 0);

	return 0;
}

LANGUAGE:

DARK MODE: